import React from 'react';
import {Table, Card, message as componentMessage, Row, Col, Popconfirm, Affix, Alert} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {Link} from 'react-router-dom';
import {PERMISSION} from './constants';
import {hasPermissions, addMonths} from './utils';
import {conventEnumValueToString, formatDateTime} from '../utils';
import {submitData, abandonData, approvePassData, approveRejectData} from './api';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {salePlanOrderStatus} from '../Enum';
import DropdownMenu from 'Shared/components/DropdownMenu';
import styles from './style.css';
import {TABLE, PAGINATION_OPTIONS, FIXED_COLUMN_WIDTH, COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT, DATETIME_FORMAT, ROWSELECTION_FIXED_COLUMN_WIDTH} from '../constants';

export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.onChangeSort = this.onChangeSort.bind(this);
        this.state = {
            loading: false,
            selectedRowKeys: [],
            prevData: this.props.data
        };
    }
    static getDerivedStateFromProps(props, state) {
        if(props.data !== state.prevData)
            return {
                prevData: props.data,
                selectedRowKeys: []
            };
        return null;
    }
    submitConfirm = id => {
        this.setState({
            loading: true
        });
        const record = this.props.data.find(d => d.id === id);
        const data = {
            id,
            rowVersion: record.rowVersion
        };
        submitData([data]).then(res => {
            this.setState({
                loading: false
            });
            if(res.ok)
                this.props.onChangeSort();
        });
    }
    
    // 避免 Popconfirm 随滚动条移动
    getPopupContainer = trigger => trigger.parentNode;

    // Popconfirm autoAdjustOverflow 仅在 render 时计算一次位置
    // Popconfirm 展开时，Affix 切换至固定状态，Popconfirm 没有自动从 Top 切换至 Botton
    // 如果存在性能问题，考虑暂时移除
    affixOnChange = () => this.forceUpdate();

    abandonConfirm = id => {
        this.setState({
            loading: true
        });
        const record = this.props.data.find(d => d.id === id);
        const data = {
            id,
            rowVersion: record.rowVersion
        };
        abandonData([data]).then(res => {
            this.setState({
                loading: false
            });
            if(res.ok)
                this.props.onChangeSort();
        });
    }
    onClickBatchAbandon = () => {
        const selectIds = this.state.selectedRowKeys;
        if(selectIds.length === 0)
            componentMessage.warning(this.props.intl.formatMessage({
                id: 'tablePanel.btn.ValidationMessage',
                defaultMessage: '请选择需要批量操作的单据'
            }));
        else {
            this.setState({loading: true});
            const data = this.props.data.filter(item => selectIds.includes(item.id)).map(item => ({
                id: item.id,
                rowVersion: item.rowVersion
            }));
            abandonData(data).then(res => {
                this.setState({loading: false});
                if(res.ok) {
                    this.props.onChangeSort();
                    this.onEndBatchOperationAbandon();
                }
            });
        }
    }
    onClickBatchSubmit = () => {
        const selectIds = this.state.selectedRowKeys;
        if(selectIds.length === 0)
            componentMessage.warning(this.props.intl.formatMessage({
                id: 'tablePanel.btn.ValidationMessage',
                defaultMessage: '请选择需要批量操作的单据'
            }));
        else {
            this.setState({loading: true});
            const data = this.props.data.filter(item => selectIds.includes(item.id)).map(item => ({
                id: item.id,
                rowVersion: item.rowVersion
            }));
            submitData(data).then(res => {
                this.setState({loading: false});
                if(res.ok) {
                    this.props.onChangeSort();
                    this.onEndBatchOperationSubmit();
                }
            });
        }
    }
    onClickBatchPass = () => {
        const selectIds = this.state.selectedRowKeys;
        if(selectIds.length === 0)
            componentMessage.warning(this.props.intl.formatMessage({
                id: 'tablePanel.btn.ValidationMessage',
                defaultMessage: '请选择需要批量操作的单据'
            }));
        else {
            this.setState({loading: true});
            const data = this.props.data.filter(item => selectIds.includes(item.id)).map(item => ({
                id: item.id,
                rowVersion: item.rowVersion
            }));
            approvePassData(data).then(res => {
                this.setState({loading: false});
                if(res.ok) {
                    this.props.onChangeSort();
                    this.onEndBatchOperationApprove();
                }
            });
        }
    }
    onClickBatchReject = () => {
        const selectIds = this.state.selectedRowKeys;
        if(selectIds.length === 0)
            componentMessage.warning(this.props.intl.formatMessage({
                id: 'tablePanel.btn.ValidationMessage',
                defaultMessage: '请选择需要批量操作的单据'
            }));
        else {
            this.setState({loading: true});
            const data = this.props.data.filter(item => selectIds.includes(item.id)).map(item => ({
                id: item.id,
                rowVersion: item.rowVersion
            }));
            approveRejectData(data).then(res => {
                this.setState({loading: false});
                if(res.ok) {
                    this.props.onChangeSort();
                    this.onEndBatchOperationApprove();
                }
            });
        }
    }
    onEndBatchOperationAbandon = () => {
        this.setState({selectedRowKeys: []});
        this.props.onEndBatchOperationAbandon();
    }
    onEndBatchOperationSubmit = () => {
        this.setState({selectedRowKeys: []});
        this.props.onEndBatchOperationSubmit();
    }
    onEndBatchOperationApprove = () => {
        this.setState({selectedRowKeys: []});
        this.props.onEndBatchOperationApprove();
    }
    onSelectedChange = keys => this.setState({selectedRowKeys: keys});
    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };
    render() {
        const {formatMessage} = this.props.intl;
        const {pageIndex, pageSize, total} = this.props;
        const locale = {
            emptyText: this.props.hasError ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        const pagination = {
            total,
            pageSize,
            current: pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const isBatchOperatting = this.props.isShowBatchAbandonPanel;
        const isBatchOperattings = this.props.isShowBatchSubmitPanel;
        const isBatchOperattingApprove = this.props.isShowBatchApprovePanel;
        const operats = [];
        if(isBatchOperatting)
            operats.push('abandon');
        if(isBatchOperattings)
            operats.push('submit');
        if(isBatchOperattingApprove)
            operats.push('approve');
        const rowSelection = (isBatchOperatting || isBatchOperattings || isBatchOperattingApprove) ? {
            fixed: true,
            type: 'checkbox',
            columnWidth: ROWSELECTION_FIXED_COLUMN_WIDTH,
            getCheckboxProps: record => ({
                disabled: !record.options.some(v => operats.includes(v))
            }),
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: this.onSelectedChange
        } : undefined;
        const abandonMessage = (<Row>
            <Col span={18}>{
                formatMessage({
                    id: 'tablePanel.Validation.Message',
                    defaultMessage: '正在进行批量操作，点击右侧关闭将退出操作'
                })
            }</Col>
            <Col span={6} className="col-align-right">
                <Popconfirm id="batchAbandon" key="batchAbandon" getPopupContainer={this.getPopupContainer} title={formatMessage({
                    id: 'tablePanel.Validation.isContinue',
                    defaultMessage: '是否继续?'
                })} okText={formatMessage({
                    id: 'tablePanel.btn.Confirm',
                    defaultMessage: '确认'
                })}
                cancelText={formatMessage({
                    id: 'tablePanel.btn.Cancel',
                    defaultMessage: '取消'
                })} onConfirm={this.onClickBatchAbandon}>
                    <a className={styles.panelalertMessage} >{formatMessage({
                        id: 'tablePanel.btn.BatchAbandon',
                        defaultMessage: '批量作废'
                    })}</a>
                </Popconfirm>
            </Col>
        </Row>);
        const approveMessage = (<Row>
            <Col span={18}>{
                formatMessage({
                    id: 'tablePanel.Validation.Message',
                    defaultMessage: '正在进行批量操作，点击右侧关闭将退出操作'
                })
            }</Col>
            <Col span={6} className="col-align-right">
                <Popconfirm id="batchPass" key="batchPass" getPopupContainer={this.getPopupContainer} title={formatMessage({
                    id: 'tablePanel.Validation.isContinue',
                    defaultMessage: '是否继续?'
                })} okText={formatMessage({
                    id: 'tablePanel.btn.Confirm',
                    defaultMessage: '确认'
                })}
                cancelText={formatMessage({
                    id: 'tablePanel.btn.Cancel',
                    defaultMessage: '取消'
                })} onConfirm={this.onClickBatchPass}>
                    <a className={styles.panelalertMessage} >{formatMessage({
                        id: 'tablePanel.btn.BatchPass',
                        defaultMessage: '批量通过'
                    })}</a>
                </Popconfirm>
                <Popconfirm id="batchReject" key="batchReject" getPopupContainer={this.getPopupContainer} title={formatMessage({
                    id: 'tablePanel.Validation.isContinue',
                    defaultMessage: '是否继续?'
                })} okText={formatMessage({
                    id: 'tablePanel.btn.Confirm',
                    defaultMessage: '确认'
                })}
                cancelText={formatMessage({
                    id: 'tablePanel.btn.Cancel',
                    defaultMessage: '取消'
                })} onConfirm={this.onClickBatchReject}>
                    <a className={styles.panelalertMessage} >{formatMessage({
                        id: 'tablePanel.btn.BatchReject',
                        defaultMessage: '批量驳回'
                    })}</a>
                </Popconfirm>
            </Col>
        </Row>);
        const submitMessage = (<Row>
            <Col span={18}>{
                formatMessage({
                    id: 'tablePanel.Validation.Message',
                    defaultMessage: '正在进行批量操作，点击右侧关闭将退出操作'
                })
            }</Col>
            <Col span={6} className="col-align-right">
                <Popconfirm id="batchSubmit" key="batchSubmit" getPopupContainer={this.getPopupContainer} title={formatMessage({
                    id: 'tablePanel.Validation.isContinue',
                    defaultMessage: '是否继续?'
                })} okText={formatMessage({
                    id: 'tablePanel.btn.Confirm',
                    defaultMessage: '确认'
                })}
                cancelText={formatMessage({
                    id: 'tablePanel.btn.Cancel',
                    defaultMessage: '取消'
                })} onConfirm={this.onClickBatchSubmit}>
                    <a className={styles.panelalertMessage} >{formatMessage({
                        id: 'tablePanel.btn.BatchSubmit',
                        defaultMessage: '批量提交'
                    })}</a>
                </Popconfirm>
            </Col>
        </Row>);
        const columns = [{
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.brand',
                defaultMessage: '品牌'
            }),
            dataIndex: 'brand',
            render: (text, record) => `(${record.brandCode})${record.brandName}`
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.planCode',
                defaultMessage: '计划编号'
            }),
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'planCode' && this.props.sortedOrder,
            render: (text, record) => <Link key="detail" to={routes.detail.format(record.id)}>{text}</Link>,
            dataIndex: 'planCode',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.marketDepartmentName',
                defaultMessage: '大区名称'
            }),
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'marketDepartmentName' && this.props.sortedOrder,
            dataIndex: 'marketDepartmentName',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.country',
                defaultMessage: '国家'
            }),
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'country' && this.props.sortedOrder,
            dataIndex: 'country',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.dealerCode',
                defaultMessage: '总代编号'
            }),
            dataIndex: 'dealerCode',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'dealerCode' && this.props.sortedOrder,
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.dealerName',
                defaultMessage: '总代名称'
            }),
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'dealerName' && this.props.sortedOrder,
            dataIndex: 'dealerName',
        },
        {
            title: addMonths(2) + this.props.intl.formatMessage({
                id: 'tablePanel.column.n1Quantity',
                defaultMessage: '月总数量'
            }),
            dataIndex: 'n1Quantity',
        },
        {
            title: addMonths(2) + this.props.intl.formatMessage({
                id: 'tablePanel.column.n1ModelCount',
                defaultMessage: '月车型种类数'
            }),
            dataIndex: 'n1ModelCount',
        },
        {
            title: addMonths(2) + this.props.intl.formatMessage({
                id: 'tablePanel.column.n1VersionCount',
                defaultMessage: '月版型种类数'
            }),
            dataIndex: 'n1VersionCount',
        },
        {
            title: addMonths(2) + this.props.intl.formatMessage({
                id: 'tablePanel.column.n1MaterialGroupCount',
                defaultMessage: '月物料组种类数'
            }),
            dataIndex: 'n1MaterialGroupCount',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.submitYear',
                defaultMessage: '提报年份'
            }),
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'submitYear' && this.props.sortedOrder,
            dataIndex: 'submitYear',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.submitMonth',
                defaultMessage: '提报月份'
            }),
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'submitMonth' && this.props.sortedOrder,
            dataIndex: 'submitMonth',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.status',
                defaultMessage: '状态'
            }),
            dataIndex: 'status',
            render: text => conventEnumValueToString(salePlanOrderStatus, text)
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.creatorName',
                defaultMessage: '创建人'
            }),
            dataIndex: 'creatorName',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.createTime',
                defaultMessage: '创建时间'
            }),
            sorter: true,
            dataIndex: 'createTime',
            sortOrder: this.props.sortedColumnKey === 'createTime' && this.props.sortedOrder,
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }];
        if(!isBatchOperatting && !isBatchOperattings && !isBatchOperattingApprove)
            columns.push({
                title: formatMessage({
                    id: 'tablePanel.column.operate',
                    defaultMessage: '操作'
                }),
                dataIndex: 'operate',
                width: FIXED_COLUMN_WIDTH,
                fixed: 'right',
                render: (t, r) => {
                    const menus = [
                        {
                            id: PERMISSION.update,
                            children: (
                                <Link key="update" to={routes.update.format(r.id)}>
                                    {this.props.intl.formatMessage({
                                        id: 'tablePanel.operation.update',
                                        defaultMessage: '编辑'
                                    })}
                                </Link>
                            ),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update))
                        },
                        {
                            id: PERMISSION.submit,
                            children: (ref =>
                                <WrappedPopconfirm
                                    key="submit"
                                    placement="topLeft"
                                    onConfirm={this.submitConfirm}
                                    onVisibleChange={ref.setMenuVisible}
                                    id={r.id}
                                    title={formatMessage({
                                        id: 'tablePanel.message.submit',
                                        defaultMessage: '是否确认提交？'
                                    })}>
                                    <a>{formatMessage({
                                        id: 'tablePanel.operation.submit',
                                        defaultMessage: '提交'
                                    })}</a>
                                </WrappedPopconfirm>
                            ),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.submit) && hasPermissions(r.options, PERMISSION.submit))
                        },
                        {
                            id: PERMISSION.approve,
                            children: (
                                <Link key="approve" to={routes.approve.format(r.id)}>
                                    {this.props.intl.formatMessage({
                                        id: 'tablePanel.operation.approve',
                                        defaultMessage: '审核'
                                    })}
                                </Link>
                            ),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.approve) && hasPermissions(r.options, PERMISSION.approve))
                        },
                        {
                            id: PERMISSION.abandon,
                            children: (ref =>
                                <WrappedPopconfirm
                                    key="abandon"
                                    placement="topLeft"
                                    onConfirm={this.abandonConfirm}
                                    onVisibleChange={ref.setMenuVisible}
                                    id={r.id}
                                    title={formatMessage({
                                        id: 'tablePanel.message.abandon',
                                        defaultMessage: '是否确认作废？'
                                    })}>
                                    <a>{formatMessage({
                                        id: 'tablePanel.operation.abandon',
                                        defaultMessage: '作废'
                                    })}</a>
                                </WrappedPopconfirm>
                            ),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon))
                        },
                    ];
                    return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
                }
            });
        return (
            <Card>
                {isBatchOperattings && <Affix offsetTop={0} className={styles.alertMargin} onChange={this.affixOnChange}>
                    <Alert message={submitMessage} type="warning" closable showIcon
                        closeText={<span className={styles.closeText}>{formatMessage({
                            id: 'tablePanel.btn.close',
                            defaultMessage: '关闭'
                        })}</span>} onClose={this.onEndBatchOperationSubmit} />
                </Affix>}
                {isBatchOperattingApprove && <Affix offsetTop={0} className={styles.alertMargin} onChange={this.affixOnChange}>
                    <Alert message={approveMessage} type="warning" closable showIcon
                        closeText={<span className={styles.closeText}>{formatMessage({
                            id: 'tablePanel.btn.close',
                            defaultMessage: '关闭'
                        })}</span>} onClose={this.onEndBatchOperationApprove} />
                </Affix>}
                {isBatchOperatting && <Affix offsetTop={0} className={styles.alertMargin} onChange={this.affixOnChange}>
                    <Alert message={abandonMessage} type="warning" closable showIcon
                        closeText={<span className={styles.closeText}>{formatMessage({
                            id: 'tablePanel.btn.close',
                            defaultMessage: '关闭'
                        })}</span>} onClose={this.onEndBatchOperationAbandon} />
                </Affix>}
                <Table
                    className={'white-space-nowrap'}
                    columns={columns}
                    dataSource={this.props.data}
                    rowSelection={rowSelection}
                    loading={this.props.loading || this.state.loading}
                    onChange={this.onChangeSort}
                    pagination={pagination}
                    rowKey="id"
                    locale={locale}
                    {...TABLE}/>
            </Card>
        );
    }
}
TablePanel.propTypes = {
    conditions: PropTypes.object.isRequired,
    data: PropTypes.array.isRequired,
    hasError: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    onEndBatchOperationAbandon: PropTypes.func.isRequired,
    onEndBatchOperationApprove: PropTypes.func.isRequired,
    onEndBatchOperationSubmit: PropTypes.func.isRequired,
    intl: PropTypes.object,
    isShowBatchAbandonPanel: PropTypes.bool,
    isShowBatchApprovePanel: PropTypes.bool,
    isShowBatchSubmitPanel: PropTypes.bool,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};
import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch, clearBatchData, clearBatchSubmit, clearBatchApprove} from './actions';
import {injectIntl} from './intl';

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const mapStateToProps = state => ({
    conditions: getConditions(state),
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    hasError: state.getIn(['page', 'domainData', 'list', 'hasError']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    permissions: getPermissions(state),
    isShowBatchAbandonPanel: state.getIn(['page', 'ui', 'showBatchAbandonPanel']),
    isShowBatchSubmitPanel: state.getIn(['page', 'ui', 'showBatchSubmitPanel']),
    isShowBatchApprovePanel: state.getIn(['page', 'ui', 'showBatchApprovePanel']),
});

const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
    onEndBatchOperationAbandon: () => dispatch(clearBatchData()),
    onEndBatchOperationSubmit: () => dispatch(clearBatchSubmit()),
    onEndBatchOperationApprove: () => dispatch(clearBatchApprove()),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));


